<template>
  <div class="app-container">
    <el-card>
      <el-page-header @back="goBack">
        <template #content>
          <div class="flex items-center">
            <div v-if="!route.query.id">新增入库单</div>
            <div v-else>
              <span
                class="text-sm mr-2"
                style="color: var(--el-text-color-regular)"
              >
                入库单编码:
              </span>
              <el-tag>{{ route.query.code }}</el-tag>
            </div>
          </div>
        </template>

        <template #extra>
          <div class="flex items-center" v-if="!route.query.readonly">
            <el-button type="primary" @click="submitForm">保 存</el-button>
          </div>
        </template>
      </el-page-header>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-collapse v-model="activeNames">
        <el-collapse-item disabled title="基本信息" name="1">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">基本信息</span>
          </template>
          <div>
            <el-form
              :model="form"
              :rules="rules"
              :disabled="route.query.readonly"
              ref="materialReceiptRef"
              label-width="100px"
            >
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="供应商名称" prop="supplierName">
                    <el-input
                      v-model="form.supplierName"
                      readonly
                      placeholder="请选择供应商"
                      @click="openDialog"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="入库日期" prop="inDate">
                    <el-date-picker
                      style="width: 100%"
                      v-model="form.inDate"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      type="datetime"
                      placeholder="请选择时间"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="创建人" prop="createBy">
                    <el-input v-model="form.createBy" readonly placeholder="" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="备注">
                    <el-input
                      v-model="form.remark"
                      type="textarea"
                      placeholder="请输入内容"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
        <el-collapse-item disabled title="入库明细" name="2">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">入库明细</span>
          </template>
          <el-button
            style="margin-bottom: 10px"
            type="primary"
            size="small"
            @click="handleMateriel"
            :disabled="route.query.readonly"
            >从物料库选择</el-button
          >
          <el-table
            v-loading="loading"
            class="table-form"
            :data="mesMaterialIndetailList"
            :header-cell-class-name="must"
          >
            <el-table-column
              label="序号"
              width="60"
              type="index"
              align="center"
              :header-cell-class-name="must"
            >
            </el-table-column>
            <el-table-column
              label="物料分类"
              min-width="120"
              align="center"
              prop="belongClass"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="物料编码"
              min-width="120"
              align="center"
              prop="code"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="自有编码"
              min-width="120"
              align="center"
              prop="originalCode"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="物料名称"
              min-width="120"
              align="center"
              prop="name"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="规格型号"
              min-width="120"
              align="center"
              prop="specs"
            >
            </el-table-column>
            <el-table-column label="单位" align="center" prop="unit">
              <template #default="scope">
                <dict-tag
                  :options="mes_material_unit"
                  :value="scope.row.unit"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="数量"
              prop="quantity"
              align="center"
              width="130"
            >
              <template #default="scope">
                <el-input
                  v-model="scope.row.quantity"
                  @input="handleAssign(scope.row)"
                  :disabled="route.query.readonly"
                  type="number"
                  @blur="sumamount(scope.row)"
                  placeholder="请输入数量"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="单价"
              prop="price"
              align="center"
              width="130"
            >
              <!--                            <template #default="scope">-->
              <!--                                <el-input v-model="scope.row.price" :disabled="route.query.readonly" type="number"-->
              <!--                                    @change="sumamount(scope.row)" placeholder="请输入单价" />-->
              <!--                            </template>-->
            </el-table-column>
            <el-table-column
              label="金额"
              prop="amount"
              disabled
              align="center"
              width="120"
            >
            </el-table-column>
            <!--                        <el-table-column label="库存数量" prop="stockNum" disabled align="center" width="120">-->

            <!--                        </el-table-column>-->
            <el-table-column
              label="备注"
              prop="remark"
              align="center"
              width="120"
            >
              <template #default="scope">
                <el-input
                  v-model="scope.row.remark"
                  :disabled="route.query.readonly"
                  placeholder="请输入备注"
                />
              </template>
            </el-table-column>

            <el-table-column
              label="操作"
              align="center"
              fixed="right"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-tooltip content="删除" placement="top">
                  <el-button
                    link
                    type="primary"
                    icon="Delete"
                    @click="handleDelete(scope.row)"
                    :disabled="route.query.readonly"
                  ></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </el-card>
    <treeChoice
      :visible="treeDialog"
      @changeUpdate="changetreerData"
      @cancel="
        () => {
          treeDialog = false;
        }
      "
    >
    </treeChoice>
    <SearchSupplier
      :visible="searchVisible"
      :status="searchStatus"
      @changeUpdate="changeSupplierData"
      @cancel="
        () => {
          searchVisible = false;
        }
      "
    ></SearchSupplier>
  </div>
</template>

<script setup>
import {
  updateMaterialin,
  getMaterialin,
  addMaterialin,
} from "@/api/storage/materialReceipt.js";
import treeChoice from "./MaterielList.vue";
import SearchSupplier from "@/components/SearchSupplier";
import useTagsViewStore from "@/store/modules/tagsView";
import useUserStore from "@/store/modules/user";
import { ElMessage } from "element-plus";
const tagsViewStore = useTagsViewStore();
const { proxy } = getCurrentInstance();
const { mes_material_unit } = proxy.useDict("mes_material_unit");
const route = useRoute();
const router = useRouter();
const activeNames = ["1", "2"];
const materialReceiptRef = ref(null);
const searchStatus = "0";
const loading = ref(false);
const userInfo = useUserStore();
const mesMaterialIndetailList = ref([]);
const searchVisible = ref(false);
const treeDialog = ref(false);
const data = reactive({
  form: {},
  rules: {
    supplierName: [
      { required: true, message: "供应商不能为空", trigger: "change" },
    ],
    inDate: [
      {
        required: true,
        message: "入库日期不能为空",
        trigger: ["blur", "change"],
      },
    ],
    createBy: [
      { required: true, message: "制单人不能为空", trigger: ["blur"] },
    ],
  },
});

const { form, rules } = toRefs(data);
if (route.query.id) {
  getMaterialin(route.query.id).then((response) => {
    form.value = response.data;
    mesMaterialIndetailList.value = response.data.mesMaterialIndetailList;
    mesMaterialIndetailList.value.forEach((item) => {
      item.belongClass = item.className;
      item.code = item.materialCode;
      item.name = item.materialName;
    });
  });
} else {
  form.value = {};
  form.value.createBy = userInfo.name;
}

// 获取当前时间
const getCurrentDateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");
  form.value.inDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
getCurrentDateTime();
// 打开供应商页面
const openDialog = () => {
  searchVisible.value = true;
};
// 选中的供应商
const changeSupplierData = (row) => {
  form.value.supplierCode = row.supplierCode;
  form.value.supplierName = row.name;
  searchVisible.value = false;
};
//选择物料
const handleMateriel = () => {
  treeDialog.value = true;
};
// const changetreerData = (row) => {
//     console.log('row', row)
//     row.forEach(each => {
//         mesMaterialIndetailList.value.push({ belongClass: each.belongClass, code: each.code, name: each.name, specs: each.specs, unit: each.unit, materialId: each.id })
//     })
//     // 创建一个对象来记录已经出现过的 materialId
//     const seenMaterialIds = {};
//     // 使用 reduce 方法遍历现有数组，并创建一个新数组来存储去重后的结果
//     const uniqueMaterialIndetailList = mesMaterialIndetailList.value.reduce((acc, curr) => {
//         // 如果当前项的 materialId 没有在 seenMaterialIds 中出现过，则将其添加到新数组中，并将其 materialId 记录在 seenMaterialIds 中
//         if (!seenMaterialIds[curr.materialId]) {
//             seenMaterialIds[curr.materialId] = true; // 记录 materialId 已经出现过
//             acc.push(curr); // 将当前项添加到新数组中
//         }
//         return acc;
//     }, []);
//     // 清空原数组
//     mesMaterialIndetailList.value = [];
//     // 将去重后的数组赋值回原数组
//     uniqueMaterialIndetailList.forEach(item => {
//         mesMaterialIndetailList.value.push(item);
//     });

//     treeDialog.value = false
// }

const changetreerData = (row) => {
  row.forEach((each) => {
    mesMaterialIndetailList.value.push({
      belongClass: each.belongClass,
      code: each.code,
      name: each.name,
      specs: each.specs,
      unit: each.unit,
      materialId: each.id,
      price: each.realtimePrice,
      originalCode: each.originalCode,
    });
  });

  // 去重
  mesMaterialIndetailList.value = uniqueByMaterialId(
    mesMaterialIndetailList.value
  );

  treeDialog.value = false;
};

const uniqueByMaterialId = (list) => {
  const seenMaterialIds = {};
  return list.reduce((acc, curr) => {
    if (!seenMaterialIds[curr.materialId]) {
      seenMaterialIds[curr.materialId] = true;
      acc.push(curr);
    }
    return acc;
  }, []);
};
const sumamount = (row) => {
  console.log("row", row);
  row.amount = Number(
    Number(row.stockNum || 0) * Number(row.price || 0)
  ).toFixed(4);
  console.log("amount:", row.amount);
};
// 删除
const handleDelete = (row) => {
  proxy.$modal.confirm("是否确认删除该数据？").then(function () {
    const index = mesMaterialIndetailList.value.findIndex(
      (item) => item.code == row.code
    );
    if (index != -1) {
      mesMaterialIndetailList.value.splice(index, 1);
      proxy.$modal.msgSuccess("删除成功");
    } else {
      proxy.$modal.msgError("未找到要删除的数据");
    }
  });
};
// 确认
const submitForm = () => {
  const hasEmptyAmount = mesMaterialIndetailList.value.find(
    (item) => isNaN(item.amount) || item.amount == null || item.amount == ""
  );
  if (hasEmptyAmount) {
    ElMessage({
      message: "请填写入库明细必填字段",
      type: "warning",
    });
    return;
  }
  materialReceiptRef.value.validate((valid) => {
    if (valid) {
      if (route.query.id) {
        updateMaterialin({
          ...form.value,
          mesMaterialIndetailList: mesMaterialIndetailList.value,
        }).then((res) => {
          ElMessage({
            message: "编辑成功",
            type: "success",
          });
          goBack();
        });
      } else {
        addMaterialin({
          ...form.value,
          status: 0,
          mesMaterialIndetailList: mesMaterialIndetailList.value,
        }).then((res) => {
          ElMessage({
            message: "新增成功",
            type: "success",
          });
          goBack();
        });
      }
    }
  });
};
const handleAssign = (row) => {
  row.stockNum = row.quantity;
};
const must = (obj) => {
  let mustColumns = [];
  mustColumns = [7];
  if (mustColumns.includes(obj.columnIndex)) {
    return "must";
  }
};
//  返回
const goBack = () => {
  tagsViewStore.delView(route);
  // router.go(-1)
  if (route.query.moduleCode == "searchMaterialReceipt") {
    router.push("/material/searchMaterialReceipt");
  } else {
    router.push("/material/materialReceipt");
  }
};
</script>

<style lang="scss" scoped>
.footer {
  text-align: center;
}

:deep(.el-pagination) {
  position: unset;
}

.table-form :deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.el-table th.must div:before) {
  content: "*";
  color: #ff1818;
}
</style>